import React, { useState } from "react";
import { Modal, Form, Input, Button } from "antd";
import type { FormProps } from "antd";
import "../../view/Login/login.css";
import { getLogin, getRegister } from "../../request";
import log from "../../assets/log.png";
// import TokenRefresh  from "../../request/useTokenRefresh";

type FieldType = {
  phone?: string;
  password?: string;
  remember?: string;
};

const MyModal = ({ isModalOpen, onClose }) => {
  const [isLoginMode, setIsLoginMode] = useState(true);
  const handleOk = () => {
    onClose();
  };

  const handleCancel = () => {
    onClose();
  };
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    const request = isLoginMode ? getLogin(values) : getRegister(values);

    request
      .then((res) => {
        console.log(res, isLoginMode ? "登录" : "注册");
        const { code } = res.data;

        if (isLoginMode) {
          if (code === 200) {
            alert("登录成功");
            let info = {
              nickname: "创客贴用户",
              userId: '92314553',
              phone: "12222222222",
              email: "未绑定",
              account: "lsk123"
            }
            localStorage.setItem("token", res.data.token);
            localStorage.setItem("userInfo", JSON.stringify(info));
            localStorage.setItem('accessToken', res.data.accessToken)
            // localStorage.setItem('refreshToken',res.data.refreshToken)
            onClose();
            window.location.reload();
          } else if (code === 500) {
            alert("未注册，去注册页面");
            setIsLoginMode(false);
          } else if (code === 401) {
            const useRegister = window.confirm("密码错误，是否去注册页面?");
            if (useRegister) {
              setIsLoginMode(false);
            }
          }
        } else {
          if (code === 200) {
            alert("注册成功,请登录");
            setIsLoginMode(true);
          } else if (code === 500) {
            alert("该手机号已经被注册了,换一个手机号");
          }
        }
      })
      .catch((error) => {
        console.log(isLoginMode ? "登录失败" : "注册失败", error);
        alert("请稍后重试");
      });

    console.log("Success:", values);
  };

  return (
    <Modal
      footer={null}
      title={isLoginMode ? "登录" : "注册"}
      open={isModalOpen}
      onOk={handleOk}
      onCancel={handleCancel}
      className="model"
    >
      <div className="log">
        <img src={log}></img>
        <div className="form">
          <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
          >
            <Form.Item
              label="手机号"
              name="phone"
              rules={[
                { required: true, message: "请输入手机号!" },
                { pattern: /^[0-9]{11}$/, message: "手机号必须是11位数字" },
              ]}
            >
              <Input />
            </Form.Item>

            {!isLoginMode && (
              <Form.Item
                label="密码"
                name="password"
                rules={[
                  { required: true, message: "请输入密码!" },
                  {
                    pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/,
                    message: "密码必须6位，包含字母和数字",
                  },
                ]}
              >
                <Input.Password />
              </Form.Item>
            )}

            {isLoginMode && (
              <Form.Item
                label="密码"
                name="password"
                rules={[
                  { required: true, message: "请输入密码!" },
                  {
                    pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/,
                    message: "密码必须6位，包含字母和数字",
                  },
                ]}
              >
                <Input.Password />
              </Form.Item>
            )}

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                {isLoginMode ? "登录" : "注册"}
              </Button>
              <Button type="link" onClick={() => setIsLoginMode(!isLoginMode)}>
                {isLoginMode ? "还没有账号？注册" : "已有账号？登录"}
              </Button>
            </Form.Item>
          </Form>
          {/* <TokenRefresh /> 在登录页面引入 TokenRefresh 组件 */}
        </div>
      </div>
    </Modal>
  );
};

export default MyModal;
